import 'whatwg-fetch';
import { message, notification } from 'antd';
import querystring from 'querystring';
const credentials = 'same-origin';

export default async (args) => {
  const p = {
    method: 'get',
    url: '',
    param: {},
    ...args
  };

  message.loading('loading', 99999999999999);

  try {
    let f;
    if (p.method.toLowerCase() === 'get') {
      f = await fetch(`${p.url}?${querystring.stringify(p.param)}`, {
        credentials: credentials
      });
    } else if (p.method.toLowerCase() === 'post') {
      f = await fetch(p.url, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify(p.param),
        credentials: credentials
      });
    } else {
      return false;
    }
    message.destroy();
    return await f.json();

  } catch (ex) {
    message.destroy();
    console.log(`%c[${p.method} fail] ${p.url}`, `color:#f24040;font-weight:600;`);
    console.log(`%c${ex}`, `color:#f24040;font-weight:600;`);
    notification.error({
      message: '服务异常',
      description: '请稍后重试',
    });
  }

}
